package com.sam.im.heiqun.uis.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.activities.NewPasswordActivity;
import com.sam.im.heiqun.uis.activities.SelectRechargeTypeActivity;
import com.sam.im.heiqun.uis.activities.SelecteATFriendActivity;
import com.sam.im.heiqun.uis.activities.SendRedPacketSelectActivity;
import com.sam.im.heiqun.uis.adapters.AtHeadAdapter;
import com.sam.im.heiqun.utils.CashierInputFilter;
import com.sam.im.heiqun.utils.EventBusTypeObject;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.fragments.BaseFragment;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class LuckyRedEnvelopeFragment extends BaseFragment implements TextWatcher {

    private static final int SELECTE_RESULT_USER = 10001;

    @BindView(R.id.red_packet_count)//红包个数
    EditText packageCount;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.edit_sendMoney)//金额
    EditText sendMoney;
    @BindView(R.id.edit_message)//留言
    EditText message;
    PasswordEditText payPSD;

    @BindView(R.id.money_count)
    TextView moneyCount;
    @BindView(R.id.explain_message)
    TextView explain;
    @BindView(R.id.change_type)
    TextView change;
    @BindView(R.id.sum_money)
    TextView moneyShow;

    @BindView(R.id.send)
    Button commit;

    @BindView(R.id.txt_title_left)
    TextView txt_title_left;
    @BindView(R.id.txt_title_right)
    TextView txt_title_right;
    @BindView(R.id.linear_num)
    LinearLayout linear_num;
    @BindView(R.id.linear_per)
    LinearLayout linear_per;

    @BindView(R.id.designated_person_ly)
    LinearLayout designated_person_ly;
    @BindView(R.id.select_per)
    RecyclerView select_per;
    private int getType = 0; //0=所有人可抢；1=指定人领取

    AtHeadAdapter mAtHeadAdapter ;
    String[] atdatas ;
    String uids = "";
    String uheads = "";

    @BindView(R.id.txt_pin)
    TextView pinImg;
    @BindView(R.id.tv_balance)
    TextView tvBalance ;
    private int sendType = 0;   // 0 拼运气    1 普通
    private AlertDialog payDialog;
    private Long groupId;
    PGService mPgService;
    private double balance;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshMoney(EventBusTypeObject ebto) {

        if (ebto.getType() == EventBusType.REFRESH_TYPE_RED_MONEY){
            try {
                balance = Double.parseDouble(ebto.getUid());
                tvBalance.setText(getActivity().getResources().getString(R.string.yu_e_1)+ebto.getUid()+getActivity().getResources().getString(R.string.yuan));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_send_red_package_group;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        try {
            balance = ((SendRedPacketSelectActivity)getActivity()).balance ;
            tvBalance.setText(getActivity().getResources().getString(R.string.yu_e_1)+balance+getActivity().getResources().getString(R.string.yuan));
        }catch (Exception e){
            e.printStackTrace();
        }
        initJ();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initAtHead(){
//        Log.i(TAG, "initAtHead: -----001-----");
        if (null==atdatas ){
//            select_per.setVisibility(View.GONE);
            atdatas = new String[0];
        }else {
//            Log.i(TAG, "initAtHead: -----001-----atdatas.length="+atdatas.length);
//            select_per.setVisibility(View.VISIBLE);
        }
//        Log.i(TAG, "initAtHead: -----002-----");
//        if (null == mAtHeadAdapter || null == atdatas){
        mAtHeadAdapter = new AtHeadAdapter(getActivity(),atdatas);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        linearLayoutManager.setStackFromEnd(false);
        select_per.setLayoutManager(linearLayoutManager);
        select_per.setAdapter(mAtHeadAdapter);
//        }else {
//            mAtHeadAdapter.notifyDataSetChanged();
//        }

    }

    public void initJ() {
        linear_num.setVisibility(View.GONE);
        designated_person_ly.setVisibility(View.GONE);
        moneyCount.setText(R.string.single_money);
        pinImg.setVisibility(View.VISIBLE);
        /*explain.setText(getResources().getString(R.string.explain_red_packet_random));
        change.setText(R.string.alter_to_normal_red_package);*/

        sendMoney.addTextChangedListener(this);
        commit.setEnabled(false);
        groupId = getActivity().getIntent().getLongExtra("destid", 0);
        mPgService = PGService.getInstance();

        InputFilter[] filters = {new CashierInputFilter()};//限定输入为金额模式
        sendMoney.setFilters(filters);
        packageCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String money = sendMoney.getText().toString().trim();
                //String trim = editable.toString().trim();
                if ("".equals(money)||0 == Double.parseDouble(money)||Double.parseDouble(money)>200) {
                    /*if (!"".equals(trim)&&Double.parseDouble(trim)==0){
                        showToast(getActivity().getResources().getString(R.string.red_packet_count1));
                        packageCount.setText("1");
                        return;
                    }*/
                    if (!"".equals(money)&&Double.parseDouble(money)>200){
                        commit.setText(getActivity().getResources().getString(R.string.one_redpacket_out200));
                    }else {
                        commit.setText(getActivity().getResources().getString(R.string.send_red_package));
                    }
                    int pageCount = 1 ;
                   /* try {
                       // pageCount = Integer.parseInt(trim);
                    }catch (Exception e){
                        e.printStackTrace();
                        packageCount.setText("1");
                    }*/

                 /*   if (!"".equals(trim) && pageCount > 100){
                        commit.setText(getActivity().getResources().getString(R.string.one_num_100));
                        packageCount.setText("100");
                    }*/
                    commit.setEnabled(false);
                    commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    moneyShow.setText("￥ 0.00");
                } else {
                    if (null == money || "".equals(money)) {
                        moneyShow.setText("￥ 0.00");
                        setunCanablesend();
                    } else {
                        /*if (0 == Double.parseDouble("".equals(trim)?"0": trim)) {
                            moneyShow.setText("￥ 0.00");
                            setunCanablesend();
                        } else {*/
                            if (Double.parseDouble(money)>balance){
                                commit.setText(getActivity().getResources().getString(R.string.yue_nozu));
                                commit.setEnabled(false);
                                commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                            }else {
                                commit.setText(getActivity().getResources().getString(R.string.send_red_package));
                                commit.setEnabled(true);
                                commit.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                                if (0 == sendType) {
                                    moneyShow.setText("￥ " + Double.parseDouble(money));
                                } else {
                                   // moneyShow.setText("￥ " + (Double.parseDouble(trim) * Double.parseDouble(money)));
                                }
                            }

                        }
                    }
                }

        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        //String packetCount = packageCount.getText().toString().trim();
        if (1==getType && null!=uids && !TextUtils.isEmpty(uids)){
            String []uuu = uids.split(",");
            //packetCount = "" + uuu.length ;
        }
        if ("".equals(s.toString())||0 == Double.parseDouble(s.toString())||Double.parseDouble(s.toString())>200) {
            commit.setEnabled(false);
            if (!"".equals(s.toString())&&Double.parseDouble(s.toString())>200){
                commit.setText(getActivity().getResources().getString(R.string.one_redpacket_out200));
            }else {
                commit.setText(getActivity().getResources().getString(R.string.send_red_package));
            }
            commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
            moneyShow.setText("￥ 0.00");
        } else {
           // if (null == packetCount || "".equals(packetCount)) {
               // moneyShow.setText("￥ 0.00");
                //setunCanablesend();

                if (0 == Double.parseDouble("".equals(s.toString().trim())?"0":s.toString().trim())) {
                    moneyShow.setText("￥ 0.00");
                   // setunCanablesend();
                } else {
                    if (Double.parseDouble(s.toString())>balance){
                        commit.setText(getActivity().getResources().getString(R.string.yue_nozu));
                        commit.setEnabled(false);
                        commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    }else {
                        commit.setText(getActivity().getResources().getString(R.string.send_red_package));
                        commit.setEnabled(true);
                        commit.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                        if (0 == sendType) {
                            moneyShow.setText("￥ " + Double.parseDouble(s.toString().trim()));
                        }
                    }

                }
            }
        }


    private void setunCanablesend() {
        commit.setText(getActivity().getResources().getString(R.string.send_red_package));
        commit.setEnabled(false);
        commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }


    @OnClick({R.id.change_type, R.id.send, R.id.txt_title_right, R.id.linear_per})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send:
                doSend();
                break;
            case R.id.pay_commit:
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    validatePayPwd(pwd);
                }
                break;
            case R.id.pay_cancel:
                payDialog.dismiss();
                break;

            case R.id.linear_per:
//                SelecteATFriendActivity.start
                Intent intent = new Intent(getActivity(), SelecteATFriendActivity.class);
                intent.putExtra("tag", 12);
                intent.putExtra("groupId", ""+groupId);
                intent.putExtra("uids", uids);
                startActivityForResult(intent, SELECTE_RESULT_USER);

                break;
        }
    }


    /**
     * 做发送红包的逻辑操作
     */
    private void doSend() {

        final UserEntivity user = ToolsUtils.getUser();

        if (!ToolsUtils.currentNetState(getActivity())) {
            return;
        }
        showProgress(null);
        String myUserId = ToolsUtils.getMyUserId();
        mPgService.getBalance(myUserId).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
//                Log.e(TAG, "onResultError: 发送群红包，接收用户余额出错");
                hideProgress();
            }

            @Override
            public void onNext(String s) {
                balance = Double.parseDouble(s);
                tvBalance.setText(getActivity().getResources().getString(R.string.yu_e_1)+s+getActivity().getResources().getString(R.string.yuan));

                Float balance = Float.valueOf(s);
                hideProgress();
                Float money = Float.valueOf(sendMoney.getText().toString().trim());
                if (money > balance) {
                    showToast(getString(R.string.balance_lack_please_recharge));
                    startActivity(SelectRechargeTypeActivity.class);
                } else {
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                        showToast(getString(R.string.please_set_pay_psd));
                        return;
                    }
                    showPayDialog();
                }
            }
        });
    }

    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(String pwd) {
        String payPsd = MD5.MD532(pwd);
        mPgService.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
//                    showToast("密码修改失败，请重试");
                if(isAdded()) new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_verify_defeat));
            }

            @Override
            public void onNext(String validateEntivity) {
                String money = sendMoney.getText().toString().trim();
                String liuyan = message.getText().toString().trim();
                //String num = packageCount.getText().toString().trim();
                if (null!=uids && !TextUtils.isEmpty(uids)){
                    String [] aa = uids.split(",");
                    //num = ""+aa.length;
                }
                if (null == liuyan || "".equals(liuyan)) {
                    liuyan = getResources().getString(R.string.wish_you_good_fortune_and_every_success);
                } else {
                    if (null==uids || TextUtils.isEmpty(uids)){
                        //sendRedPacket("" + groupId, money, liuyan, num, "");
                        sendLuckRedPacket("" + groupId, money, liuyan);
                    }else {
                        String [] aa = uids.split(",");
                        //sendRedPacket("" + groupId, money, liuyan, num, new Gson().toJson(aa));
                    }
                }
                payDialog.dismiss();
            }
        });
    }


    private void showPayDialog() {
        View dialog = LayoutInflater.from(getActivity()).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(getActivity()).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(this);
        payCommit.setOnClickListener(this);
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }


    /**
     * 发送幸运红包
     *
     * @param uId
     * @param money
     * @param liuyan
     */
    public void sendLuckRedPacket(final String uId, final String money, final String liuyan) {
//        Log.e(TAG, "sendRedPacket:  群组红包---");
        Long userId= Long.parseLong(ToolsUtils.getMyUserId());//当前用户的id
        Double money1=Double.parseDouble(money);
        //Long groupId=Long.parseLong(uId);//当前用户的id
        //要传给后台的参数全部封装成json，然后加密传给后台
        /*com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("userId", userId);
        json.put("redPacketContent", liuyan);
        json.put("groupId", uId);
        json.put("money", money);
        String content = RequestRSAUtils.setRsaContent(json);*/
        mPgService.sendLuckRedPacket(userId,money1,liuyan,uId).subscribe(new AbsAPICallback<String>() {
        //mPgService.sendLuckRedPacket("userId","redPacketContent","groupId","money").subscribe(new AbsAPICallback<String>() {
            //mPgService.sendRedPacket(sendType == 0 ? "1" : "2", ToolsUtils.getMyUserId(), num, liuyan, uId, "2", money,"", limit).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                /*if(isAdded()){
                    new ToastUtils().showSingleToast(getResources().getString(R.string.send_faild));
                    Log.i("info","发送返回值"+ex);
                }*/

                Log.i("info","ex"+ex.getDisplayMessage()+ex.getCode());
                hideProgress();
                try {
                    String displayMessage = ex.getDisplayMessage();
                    JSONObject obj = new JSONObject(displayMessage);
                    JSONObject data = obj.getJSONObject("data");
                    String info = data.getString("info");
                    showToast(info+"");
                    getActivity().finish();
                }catch (Exception e){
                    ToolsUtils.showToast(getActivity(),getResources().getString(R.string.caozuo_fail));
                }

            }

            @Override
            public void onNext(String data) {
                if(isAdded()){
                    new ToastUtils().showSingleToast(getResources().getString(R.string.send_red_package_success));
                }

              /*  Intent intent = new Intent();
                intent.putExtra("destid",uId);
                intent.putExtra("money",money);
                intent.putExtra("liuyan",liuyan);
                intent.putExtra("num",num);
                intent.putExtra("sendType",sendType==0?1:2);
                intent.putExtra("redPacketId",data);
                setResult(10,intent);*/
                getActivity().finish();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case SELECTE_RESULT_USER :
                if (resultCode == getActivity().RESULT_OK){
                    uids = data.getStringExtra("uids");
                    uheads = data.getStringExtra("uheads");
                    atdatas = uheads.split(",");
                    initAtHead();
                }
                break;
        }
    }
}
